//
//  GamesTableViewController.m
//  LPSNews
//
//  Created by lanou3g on 14-10-11.
//  Copyright (c) 2014年 LPS. All rights reserved.
//

#import "GamesViewController.h"
#import "Games.h"
#import "GamesTableViewCell.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "TechDetailViewController.h"


#define Games_News @"http://c.m.163.com/nc/article/list/T1397016069906/"

static int number = 20;

@interface GamesViewController ()
@property (nonatomic, assign)AFHTTPRequestOperationManager *requestManager;
@end

@implementation GamesViewController
- (void)dealloc
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [_requestManager.operationQueue cancelAllOperations];
    [_gameArray release];
    [super dealloc];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    //1.下拉刷新(进入刷新状态会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    //2.上拉加载更多(进入刷新状态会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRefreshing)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)headerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * headerUpdataString =[Games_News stringByAppendingFormat:@"%d-20.html",0];
        [self requestWebDataForURLString:headerUpdataString andIsDowndrag:YES];
    });
}
- (void)footerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * footerUpdateString = [Games_News stringByAppendingFormat:@"%d-20.html",number];
        [self requestWebDataForURLString:footerUpdateString andIsDowndrag:NO];
    });
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _gameArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 215;
    }else
    {
        return 85;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Games * games = [self.gameArray objectAtIndex:indexPath.row];
    games.number = (int)indexPath.row;
    GamesTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"games"];
    if (cell == nil) {
        cell = [[[GamesTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"games"]autorelease];
    }
    cell.titleLabel.text = nil;
    cell.digestLabel.text = nil;
    cell.newsImageView.image = nil;
    cell.bottomLine.backgroundColor = [UIColor clearColor];
    cell.games = games;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Games * games = [_gameArray objectAtIndex:indexPath.row];
    TechDetailViewController * gamesVC = [[TechDetailViewController alloc]init];
    gamesVC.docid = games.docid;
    [self.navigationController pushViewController:gamesVC animated:NO];
    
    [gamesVC release];
}

#pragma 网络请求
- (void) tableViewDownLoadDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    if (_gameArray == nil) {
        _gameArray = [[NSMutableArray alloc] init] ;
        [self requestWebDataForURLString:urlstring andIsDowndrag:isDowndrag];
    }
}
- (void)requestWebDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag

{
    NSMutableArray *requestDataArray = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    self.requestManager = requestManager;
    [requestManager GET:urlstring  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = responseObject;
        NSArray *keyarray = [dict allKeys];
        NSString *keyString = keyarray[0];
        NSArray *techArray = [dict objectForKey:keyString];
        for (NSDictionary *dict in techArray) {
            Games * games = [[Games alloc] init];
            [games setValuesForKeysWithDictionary:dict];
            [requestDataArray addObject:games];
            [games release];
        }
        
        if (isDowndrag) {
            self.gameArray = requestDataArray;
            [self.tableView headerEndRefreshing];
            number = 20;
        }else
        {
            [self.gameArray addObjectsFromArray:requestDataArray];
            number += 20;
            [self.tableView footerEndRefreshing];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UILabel * textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 140, 100);
        textLable.center = CGPointMake(160, 240);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.text = @"网络不给力";
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view.window addSubview:textLable];
        textLable.alpha = 0;
        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                textLable.alpha = 0.8;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0;
                } completion:^(BOOL finished) {
                    [textLable removeFromSuperview];
                }];
            }];
        }];
        
        [textLable release];
        
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
        
    }];
    
    [requestDataArray release];
    
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
